﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Mysoft.Common.Configuration;
using Mysoft.Common.Extensions;
using Mysoft.Common.Jwt;
using Mysoft.Data.UserManager;
using System.Net;
using System.Security.Claims;

namespace Mysoft.AppStartup.Container.Filters
{
    public interface IVerifyAuthorize : IFilterMetadata
    {
        AuthorizationFilterContext OnAuthorization(AuthorizationFilterContext context);
    }
    /// <summary>
    /// 校验token合法性
    /// </summary>
    public class VerifyAuthorizeAttribute : Attribute, IVerifyAuthorize, IAllowAnonymous
    {
        public AuthorizationFilterContext OnAuthorization(AuthorizationFilterContext context)
        {
            string fixedoken = "";
            //如果token已失效，直接获取header里的token
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                fixedoken = context.HttpContext.Request.Headers[AppSetting.TokenHeaderName];
                fixedoken = fixedoken?.Replace("Bearer ", "");
                //判断是否传入了token
                if (string.IsNullOrEmpty(fixedoken))
                {
                    return context.Unauthorized("Token为空");
                }
                //解析token
                Guid? userId = JwtHelper.GetUserId(fixedoken);
                if (!userId.HasValue || userId == Guid.Empty)
                {
                    return context.Unauthorized("Token不正确");
                }
                //判断当前用户的token与缓存的token是否相同
                if (UserContext.Current.UserInfo.Token != fixedoken)
                {
                    return context.FilterResult(HttpStatusCode.Unauthorized, "用户会话时间已过期");
                }
                context.AddIdentity(userId);
            }
            else
            {
                fixedoken = ((ClaimsIdentity)context.HttpContext.User.Identity)?.BootstrapContext?.ToString();
            }
            //判断当前用户的token与缓存的token是否相同
            if (UserContext.Current.UserInfo.Token != fixedoken)
            {
                return context.FilterResult(HttpStatusCode.Unauthorized, "用户会话时间已过期");
            }
            return context; ;
        }
    }
}
